package api

import (
	"encoding/json"
	"fmt"
	"gitee.com/enzolwb/my-web-scaffold/models"
	"gitee.com/enzolwb/my-web-scaffold/pkg/app"
	"gitee.com/enzolwb/my-web-scaffold/pkg/app/validation"
	e "gitee.com/enzolwb/my-web-scaffold/pkg/const"
	"gitee.com/enzolwb/my-web-scaffold/pkg/ecode"
	"gitee.com/enzolwb/my-web-scaffold/pkg/util"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"time"
)

/*
	演示Demo 可删除
	主要作用是参考 验证、Session、统一返回值等写法
*/
type SessUserInfo struct {
	ID             int    `json:"id"`
	UserName       string `json:"user_name"`
	LoginTime      string `json:"login_time"`
	LoginTimeStamp int64
}

func Login(c *gin.Context) {
	var (
		obj  AuthInput
		err  error
		auth *models.Auth
	)
	if err := validation.BindValidParams(c, &obj); err != nil {
		return
	}
	data := make(map[string]string)
	code := ecode.XError
	auth, err = models.CheckAuth(obj.Username, obj.Password)
	if err == nil {
		//设置session
		now := time.Now()
		sessInfo := &SessUserInfo{
			ID:             auth.ID,
			UserName:       auth.UserName,
			LoginTime:      now.Format("2006-01-02 15:04:05"),
			LoginTimeStamp: now.Unix(),
		}
		sessBts, _ := json.Marshal(sessInfo)
		sess := sessions.Default(c)
		//session过期时间设置一下
		/*sess.Options(sessions.Options{
			MaxAge: 10,//seconds
		})*/
		sess.Set(e.SESSION_USER_INFO_KEY, string(sessBts))
		sess.Save()
		//要添加一个token 用于前端 保存在本地
		data["token"] = util.EncodeMD5(fmt.Sprintf("%d%s", auth.ID, auth.UserName))
		code = ecode.Ok
	} else {
		code = ecode.ErrAuthNotFind
	}
	app.Response(c, code, data)
	return
}
